package logic

import (
	"log"
	"math/rand"
	"mssgserver/constant"
	"mssgserver/db"
	"mssgserver/net"
	"mssgserver/server/common"
	"mssgserver/server/game/gameConfig"
	"mssgserver/server/game/global"
	"mssgserver/server/game/model"
	"mssgserver/server/game/model/data"
	"time"
)

var RoleCityService = &roleCityService{}

type roleCityService struct {
}

/*
*
初始化玩家的城市
*/
func (r *roleCityService) InitCity(role *data.Role, req *net.WsMsgReq) error {
	rc := &data.MapRoleCity{}
	ok, err := db.Engine.Table(rc).Where("rid=?", role.RId).Get(rc)
	if err != nil {
		log.Println("查询角色城市出错", err)
		return common.New(constant.DBError, "查询角色城市出错")
	}
	if !ok {
		//循环判断
		for {
			//没有城池 初始化 条件系统城市5格内不能有玩家城池
			x := rand.Intn(global.MapWith)
			y := rand.Intn(global.MapHeight)
			if r.IsCanBuild(x, y) {
				//判断是否符合创建条件
				//系统城池5格范围内，不能建玩家城池
				//建的肯定是主城
				rc.RId = role.RId
				rc.Y = y
				rc.X = x
				rc.CreatedAt = time.Now()
				rc.Name = role.NickName
				rc.CurDurable = gameConfig.Base.City.Durable
				_, err := db.Engine.Table(rc).Insert(rc)
				if err != nil {
					log.Println("插入玩家城市出错", err)
					return common.New(constant.DBError, "插入玩家城市出错")
				}
				//初始化城池内设施
				err = CityFacilityService.TryCreate(rc.CityId, role.RId, req)
				if err != nil {
					log.Println("初始化城池内设施", err)
					return common.New(constant.DBError, "初始化城池内设施")
				}
			}
		}

	}
	return nil
}

/*
*
返回角色的城市
*/
func (r *roleCityService) GetCitys(rid int) ([]model.MapRoleCity, error) {
	mr := &data.MapRoleCity{}
	mrs := make([]data.MapRoleCity, 0)
	err := db.Engine.Table(mr).Where("rid=?", rid).Find(&mrs)
	if err != nil {
		log.Println("GetRoleCitys查询数据库失败")
		return make([]model.MapRoleCity, 0), common.New(constant.DBError, "GetRoleCitys查询数据库失败")
	}
	roleCitys := make([]model.MapRoleCity, 0)
	for _, roleCity := range mrs {
		roleCitys = append(roleCitys, roleCity.ToModel().(model.MapRoleCity))
	}
	return roleCitys, nil
}

/*
*
判断是否能够创建城池
*/
func (r roleCityService) IsCanBuild(x int, y int) bool {
	confs := gameConfig.MapRes.Confs
	sysBuild := gameConfig.MapRes.SysBuild
	pIndex := global.ToPosition(x, y)
	_, ok := confs[pIndex]
	if !ok {
		return false
	}
	for _, n := range sysBuild {
		if n.Type == gameConfig.MapBuildSysCity {
			if x >= n.X-5 && x <= n.X+5 && y >= n.Y-5 && y <= n.Y+5 {
				return false
			}
		}
	}
	return true
}
